package com.csh.subject.domain.handler.subject;

import com.csh.subject.common.enums.SubjectInfoTypeEnum;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 题目类型处理程序工厂
 */
@Component
public class SubjectTypeHandlerFactory implements InitializingBean {
    //首先注注入四个策略实现类
    @Resource
    private List<SubjectTypeHandler> subjectTypeHandlerList;

    //创建一个空map集合，k为题目类型枚举，v为策略实现类，
    //初始化bean之后，map集合里就有了具体的枚举对象和对应的实现类
    private Map<SubjectInfoTypeEnum, SubjectTypeHandler> handlerMap = new HashMap<>();

    //定义getHandler方法，只需传入题目类型就能返回对应的策略实现类
    public SubjectTypeHandler getHandler(int subjectType){
        SubjectInfoTypeEnum subjectInfoTypeEnum = SubjectInfoTypeEnum.getByCode(subjectType);
        return handlerMap.get(subjectInfoTypeEnum);
    }

    //spring在该Bean的属性设置完成后,会调用afterPropertiesSet方法，初始化映射关系
    @Override
    public void afterPropertiesSet() throws Exception {
        for (SubjectTypeHandler subjectTypeHandler : subjectTypeHandlerList) {
            handlerMap.put(subjectTypeHandler.getHandlerType(), subjectTypeHandler);
        }
    }

}
